package com.smile.cloud.setaOrder.service.impl;

import com.smile.cloud.redisConfig.distributedLock.redisson.AquiredLockWorker;
import com.smile.cloud.redisConfig.distributedLock.redisson.RedissonLocker;
import com.smile.cloud.setaOrder.feign.AccountService;
import com.smile.cloud.setaOrder.feign.StorageService;
import com.smile.cloud.setaOrder.mapper.OrderMapper;
import com.smile.cloud.setaOrder.model.Order;
import com.smile.cloud.setaOrder.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 订单业务实现类
 * Created by smile on 2019/11/11.
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {


    @Resource
    private OrderMapper orderMapper;
    @Resource
    private StorageService storageService;
    @Resource
    private AccountService accountService;
    @Resource
    private RedissonLocker redissonLocker;

    private static final String CREATE_ORDER_LOCK = "create_order";

    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     */
    @Override
    @GlobalTransactional(name = "create-order", rollbackFor = Exception.class)
    public void create(Order order) throws Exception {
        redissonLocker.lock(CREATE_ORDER_LOCK, new AquiredLockWorker<Object>() {
            @Override
            public Object invokeAfterLockAquire() throws Exception {
                log.info("------->下单开始");
                //本应用创建订单
                orderMapper.create(order);

                //远程调用库存服务扣减库存
                log.info("------->order-service中扣减库存开始");
                storageService.decrease(order.getProductId(), order.getCount());
                log.info("------->order-service中扣减库存结束");

                //远程调用账户服务扣减余额
                log.info("------->order-service中扣减余额开始");
                accountService.decrease(order.getUserId(), BigDecimal.valueOf(order.getMoney()));
                log.info("------->order-service中扣减余额结束");

                //修改订单状态为已完成
                log.info("------->order-service中修改订单状态开始");
                orderMapper.update(order.getUserId(), 0);
                log.info("------->order-service中修改订单状态结束");

                log.info("------->下单结束");
                return null;
            }
        });

    }
}
